package com.example.core.convert.form;

import com.example.core.convert.utils.ConvertorUtils;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ReflectionUtils;

import javax.persistence.EntityManager;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

@Data
public class FormConvertor_IDToModelList implements FormConvertor {
    Logger logger = LoggerFactory.getLogger(getClass());
    private String property;

    private Class<?> clazz;

    public FormConvertor_IDToModelList(String property, Class<?> clazz) {
        this.property = property;
        this.clazz = clazz;
    }

    @Override
    public void convertor(Object model, Object val) throws Exception {
        EntityManager entityManager = ConvertorUtils.getInstance().getEntityManager();
        Field field = ReflectionUtils.findField(model.getClass(), this.property);
        if (field != null) {
            if (val instanceof String && ((String) val).contains(PATH)) {
                List list = new ArrayList();
                for (String id : ((String) val).split(PATH)) {
                    Object target = entityManager.find(clazz, id);
                    if (target != null) {
                        list.add(target);
                    }
                }
                if (!list.isEmpty()) {
                    field.setAccessible(true);
                    field.set(model, list);
                }
            }
        }
    }
}
